package com.awanp3.nimbus.wms.fg.controller;

import java.util.List;

import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.awanp3.nimbus.base.api.RemoteCompanyService;
import com.awanp3.nimbus.base.api.RemotePlantService;
import com.awanp3.nimbus.base.api.domain.vo.RemoteCompanyVo;
import com.awanp3.nimbus.base.api.domain.vo.RemotePlantVo;
import com.awanp3.nimbus.common.core.exception.ServiceException;
import com.awanp3.nimbus.common.core.utils.StringUtils;
import com.awanp3.nimbus.remote.api.RWmsPoInfoService;
import com.awanp3.nimbus.remote.api.domain.RemoteWmsPoInfo;
import com.awanp3.nimbus.remote.api.model.FetchOrderParam;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.awanp3.nimbus.common.idempotent.annotation.RepeatSubmit;
import com.awanp3.nimbus.common.log.annotation.Log;
import com.awanp3.nimbus.common.web.core.BaseController;
import com.awanp3.nimbus.common.mybatis.core.page.PageQuery;
import com.awanp3.nimbus.common.core.domain.R;
import com.awanp3.nimbus.common.core.validate.AddGroup;
import com.awanp3.nimbus.common.core.validate.EditGroup;
import com.awanp3.nimbus.common.log.enums.BusinessType;
import com.awanp3.nimbus.common.excel.utils.ExcelUtil;
import com.awanp3.nimbus.wms.fg.domain.vo.WmsPoInfoVo;
import com.awanp3.nimbus.wms.fg.domain.bo.WmsPoInfoBo;
import com.awanp3.nimbus.wms.fg.service.IWmsPoInfoService;
import com.awanp3.nimbus.common.mybatis.core.page.TableDataInfo;

/**
 * 采购订单
 * 前端访问路由地址为:/wms/poInfo
 *
 * @author 20014170
 * @date 2025-09-11
 */
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/poInfo")
public class WmsPoInfoController extends BaseController {

    private final IWmsPoInfoService wmsPoInfoService;

    @DubboReference
    private RWmsPoInfoService rWmsPoInfoService;

    @DubboReference
    private RemoteCompanyService remoteCompanyService;

    @DubboReference
    private RemotePlantService remotePlantService;

    /**
     * 查询采购订单分页列表
     */
    @SaCheckPermission("wms:poInfo:list")
    @GetMapping("/page")
    public TableDataInfo<WmsPoInfoVo> page(WmsPoInfoBo bo, PageQuery pageQuery) {
        return wmsPoInfoService.queryPageList(bo, pageQuery);
    }

    /**
     * 查询采购订单列表
     */
    @SaCheckPermission("wms:poInfo:list")
    @GetMapping("/list")
    public R<List<WmsPoInfoVo>> list(WmsPoInfoBo bo) {
        List<WmsPoInfoVo> list = wmsPoInfoService.queryList(bo);
        return R.ok(list);
    }


    /**
     * 导出采购订单列表
     */
    @SaCheckPermission("wms:poInfo:export")
    @Log(title = "采购订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(WmsPoInfoBo bo, HttpServletResponse response) {
        List<WmsPoInfoVo> list = wmsPoInfoService.queryList(bo);
        ExcelUtil.exportExcel(list, "采购订单", WmsPoInfoVo.class, response);
    }

    /**
     * 获取采购订单详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("wms:poInfo:query")
    @GetMapping("/{id}")
    public R<WmsPoInfoVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable("id") Long id) {
        return R.ok(wmsPoInfoService.queryById(id));
    }

    /**
     * 调用SAP接口获取PO单据
     */
    @SaCheckPermission("wms:poInfo:fetch")
    @Log(title = "PO单据获取", businessType = BusinessType.FETCH)
    @RepeatSubmit()
    @PostMapping("/fetch")
    public R<List<RemoteWmsPoInfo>> fetch(@RequestBody FetchOrderParam fetchOrderParam) {
        if (StringUtils.isEmpty(fetchOrderParam.getOrderNo())) {
            throw new ServiceException("必须传入采购订单号");
        }
        List<RemoteCompanyVo> companyList = remoteCompanyService.queryList();
        if (CollectionUtils.isEmpty(companyList)) {
            throw new ServiceException("该租户无采购订单相关业务");
        }
        companyList.forEach(company -> {
            List<RemotePlantVo> plantList = remotePlantService.queryList();
            FetchOrderParam param = new FetchOrderParam();
            param.setCompanyCode(company.getCompanyCode());
            param.setPlantCodes(plantList.stream().map(RemotePlantVo::getPlantCode).toList());
            List<RemoteWmsPoInfo> poInfoList = rWmsPoInfoService.fetch(param);
            log.info("公司{}， po行数{}", company.getCompanyName(), poInfoList.size());
        });
        return R.ok("下载成功");
    }

    /**
     * 新增采购订单
     */
    @SaCheckPermission("wms:poInfo:add")
    @Log(title = "采购订单", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody WmsPoInfoBo bo) {
        return toAjax(wmsPoInfoService.insertByBo(bo));
    }

    /**
     * 修改采购订单
     */
    @SaCheckPermission("wms:poInfo:edit")
    @Log(title = "采购订单", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody WmsPoInfoBo bo) {
        return toAjax(wmsPoInfoService.updateByBo(bo));
    }

    /**
     * 删除采购订单
     *
     * @param ids 主键串
     */
    @SaCheckPermission("wms:poInfo:remove")
    @Log(title = "采购订单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable("ids") Long[] ids) {
        return toAjax(wmsPoInfoService.deleteWithValidByIds(List.of(ids), true));
    }
}
